package com.wash.shoes.domain.dy.request;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wash.shoes.domain.dy.model.CreateBookDto;
import com.wash.shoes.domain.dy.model.QueryBookDto;
import com.wash.shoes.entity.*;
import com.wash.shoes.mapper.BrandMapper;
import com.wash.shoes.mapper.OrderGoodMapper;
import com.wash.shoes.mapper.ShopMapper;
import com.wash.shoes.request.DyDelayedOrderRecord;
import com.wash.shoes.service.CustomerService;
import com.wash.shoes.service.OrderGoodService;
import com.wash.shoes.service.OrderService;
import com.wash.shoes.util.WsRandomUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author lijianguo
 * @Date 29/03/2025 08:08
 * https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/locallife/general-ability/self-operated-trading/book/query-book
 * /生活服务/通用能力/生活服务交易系统（账号融合版）/预约/创建预约单
 * 预约
 * 1-创建预约单
 * 2-预约接单结果回调
 * 3-商家取消预约
 * 4-用户取消预约
 * 5-查询预约单信息
 * 6-预约接单超时回调
 * 7-预约取消/完成通知
 **/
@Log4j2
@Component
public class DyBookRequest extends DyBaseRequest {

    @Autowired
    CustomerService customerService;

    @Autowired
    OrderGoodService orderGoodService;

    @Autowired
    OrderService orderService;

    /**
     * 预约 查询预约单信息
     * <p>
     * 预约状态
     * BOOKING 预约中
     * SUCCESS 预约成功
     * FINISH 预约完成(已核销）
     * CANCEL 预约取消
     * FAIL 预约失败
     *
     * @param orderPo 订单信息
     * @return 预约单状态
     */
    public String queryBook(OrderPo orderPo, OrderGoodPo orderGoodPo) {
        BrandPo brandPo = getBrandPo(orderPo);
        QueryBookDto queryBookVo = new QueryBookDto();
        queryBookVo.setBook_id(orderPo.isNewBook() ? orderGoodPo.getDyBookId() : orderPo.getDyBookId());
        String result = postRequest(DyConstant.QUERY_BOOK_POST, queryBookVo, brandPo.getAccountid());
        //判断是否成功
        if (DY_SUCCESS_CODE.equals(JSONObject.parseObject(result).getJSONObject("extra").getString("error_code"))) {
            return JSONObject.parseObject(result).getJSONObject("data").getJSONArray("book_info_list").getJSONObject(0).getString("status");
        }
        return "QUERY_BOOK_CUSTRM_FAIL";
    }

    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private ShopMapper shopMapper;

    //创建抖音预约单使用延迟队列去创建

    public static final DelayQueue<DyDelayedOrderRecord> CREATE_BOOK_DELAY_QUEUE = new DelayQueue<DyDelayedOrderRecord>();

    /**
     * 1-创建预约单
     */
    public OrderPo createBookPost(OrderPo orderPo) {

        CustomerPo customerPo = customerService.getById(orderPo.getCustomId());
        List<OrderGoodPo> orderGoodPoList = orderGoodService.getOrderGoods(orderPo.getId());
        BrandPo brandPo = getBrandPo(orderPo);
        ShopPo shopPo = shopMapper.selectById(orderPo.getShopId());
        Assert.notNull(shopPo, "店铺不存在,shopId:" + orderPo.getShopId());

//        createBookDto.setAccount_id(brandPo.getAccountid());//设置抖音的accountid

        for (OrderGoodPo orderGoodPo : orderGoodPoList) {
            List<CreateBookDto.ItemBookInfo> itemBookInfoList = new ArrayList<>();
            CreateBookDto createBookDto = new CreateBookDto();
            createBookDto.setOrder_id(orderPo.getMtOrderId());
            // 这个out book no 只能用一次,每次都要新的
            createBookDto.setOut_book_no(orderPo.getOrderNo() + "_" + WsRandomUtil.generateByRandom(10));
            createBookDto.setOpen_id(customerPo.getDyOpenId());
            CreateBookDto.ItemBookInfo itemBookInfo = new CreateBookDto.ItemBookInfo();

            itemBookInfo.setPoi_id(shopPo.getPoId());
            itemBookInfo.setShop_name(shopPo.getShopName());
            itemBookInfo.setExt_shop_id(shopPo.getPoId());

            itemBookInfo.setGoods_id(orderGoodPo.getGoodsId());
            // 173 272 320 0000 当前的时间可以预约
            itemBookInfo.setBook_start_time(Long.parseLong(orderPo.getShoeCollectionDate()));
            // 120天的有效期
            itemBookInfo.setBook_end_time(System.currentTimeMillis() + 120L * 24 * 60 * 60 * 1000);

            // BookSkuInfo
            CreateBookDto.BookSkuInfo bookSkuInfo = new CreateBookDto.BookSkuInfo();
            bookSkuInfo.setPrice((int) (orderGoodPo.getPrice() * 100 /** orderGoodPo.getBuyNum()*/));
            bookSkuInfo.setSku_id(orderGoodPo.getGoodsId());
            bookSkuInfo.setSku_id_type(1);
            itemBookInfo.setBook_sku_info(bookSkuInfo);

            itemBookInfoList.add(itemBookInfo);
            createBookDto.setItem_book_info_list(itemBookInfoList);
            // 等一下确认预约,抖音的数据保存起来
            //放入延迟队列,1分钟后执行去创建预约单
            log.info("延迟队列添加预约单,延迟5秒执行,orderId:{},createBook:{}", orderPo.getId(), JSONUtil.toJsonStr(createBookDto));
            DyBookRequest.CREATE_BOOK_DELAY_QUEUE.add(new DyDelayedOrderRecord(createBookDto, brandPo.getAccountid(), TimeUnit.SECONDS.toMillis(5), orderPo.getOrderNo(), orderPo.getId(), 0, orderGoodPo.getItemOrderId()));
        }

        return orderPo;
    }

    /**
     * 开发者可调用该接口通知开放平台预约接单结果
     *
     * @param orderPo
     */
    public boolean bookResultCallback(OrderPo orderPo, OrderGoodPo orderGoodPo) {
        HashMap<String, Object> request = new HashMap<>();
        String bookId = orderPo.isNewBook() ? orderGoodPo.getDyBookId() : orderPo.getDyBookId();
        request.put("book_id", bookId);
        request.put("result", 1);
        /** {"extra":{"error_code":0,"description":"success","sub_error_code":0,"sub_description":"","logid":
         "20250331151828BBC5BACEFA0A35043373","now":1743405509},"data":{"error_code":0,"description":"success"}} **/
        BrandPo brandPo = getBrandPo(orderPo);
        String result = postRequest(DyConstant.BOOK_RESULT_CALLBACK_POST, request, brandPo.getAccountid());
        log.info("预约接单结果回调orderId:" + orderPo.getId() + ",bookid:" + bookId + ",result:" + result);
        return DY_SUCCESS_CODE.equals(JSONObject.parseObject(result).getJSONObject("extra").getString("error_code"));
    }


    public static void main(String[] args) {
        String s = "{\"extra\":{\"error_code\":0,\"description\":\"系统异常订单不存在\",\"sub_error_code\":13000,\"sub_description\":\"系统异常订单不存在\",\"logid\":\"202509021554295A34691E4BF0621ADCFF\",\"now\":1756799669},\"data\":{\"error_code\":13000,\"description\":\"系统异常订单不存在\"}}";
        System.out.println(DY_SUCCESS_CODE.equals(JSONObject.parseObject(s).getJSONObject("extra").getString("error_code")));
    }

    /**
     * 抖音成功码
     */
    public static final String DY_SUCCESS_CODE = "0";
    @Autowired
    private OrderGoodMapper orderGoodMapper;

    /**
     * 开发者可调用该接口通知开放平台预约接单结果
     */
    public String userCancelBookPost(OrderPo orderPo) {
        CustomerPo customerPo = customerService.getById(orderPo.getCustomId());
        BrandPo brandPo = getBrandPo(orderPo);
        List<OrderGoodPo> data = orderGoodMapper.selectList(new LambdaQueryWrapper<OrderGoodPo>().eq(OrderGoodPo::getOrderId, orderPo.getId()));
        StringBuilder sb = new StringBuilder();
        if (CollectionUtil.isNotEmpty(data)) {
            data.forEach(e -> {
                JSONObject request = new JSONObject();
                request.put("book_id", e.getDyBookId());
                request.put("open_id", customerPo.getDyOpenId());
                JSONArray cancelReason = new JSONArray();
                cancelReason.add(orderPo.getRemark());
                request.put("cancel_reason", cancelReason);
                String result = postRequest(DyConstant.USER_CANCEL_BOOK_POST, request, brandPo.getAccountid());
                sb.setLength(0);
                sb.append(result);
            });
        }

        JSONObject resultObj = JSONObject.parseObject(sb.toString());
        return resultObj.getJSONObject("data").getString("description");
    }

    /**
     * 开发者可调用该接口通知开放平台预约接单结果
     */
    public String userCancelBookPost1(OrderPo orderPo) {
        CustomerPo customerPo = customerService.getById(orderPo.getCustomId());
        JSONObject request = new JSONObject();
        request.put("book_id", orderPo.getDyBookId());
        request.put("open_id", customerPo.getDyOpenId());
        BrandPo brandPo = getBrandPo(orderPo);
        JSONArray cancelReason = new JSONArray();
        cancelReason.add(orderPo.getRemark());
        request.put("cancel_reason", cancelReason);
        String result = postRequest(DyConstant.USER_CANCEL_BOOK_POST, request, brandPo.getAccountid());
        JSONObject resultObj = JSONObject.parseObject(result);
        return resultObj.getJSONObject("data").getString("description");
    }


    /**
     * 商家取消预约
     */
    public String merchantCancelBookPost(OrderPo orderPo) {
        List<OrderGoodPo> data = orderGoodMapper.selectList(new LambdaQueryWrapper<OrderGoodPo>().eq(OrderGoodPo::getOrderId, orderPo.getId()));
        StringBuilder sb = new StringBuilder();
        if (CollectionUtil.isNotEmpty(data)) {
            data.forEach(e -> {
                JSONObject request = new JSONObject();
                request.put("book_id", e.getDyBookId());
                String cancelReason;
                if (StrUtil.isNotBlank(orderPo.getRemark())) {
                    cancelReason = orderPo.getRemark();
                } else {
                    cancelReason = "用户不想要";
                }
                BrandPo brandPo = getBrandPo(orderPo);
                request.put("cancel_reason", cancelReason);
                String result = postRequest(DyConstant.MERCHANT_CANCEL_BOOK_POST, request, brandPo.getAccountid());
                sb.setLength(0);
                sb.append(result);
            });
        }
        return sb.toString();
    }
}
